package com.example.patentback.controller;

import com.example.patentback.entity.*;
import com.example.patentback.service.*;
import com.example.patentback.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/patent")
public class PatentController {

    @Autowired
    PatentService patentService;

    @Autowired
    PatentApplicantService patentApplicantService;

    @Autowired
    ApplicantService applicantService;

    @Autowired
    DocumentService documentService;

    @Autowired
    HelperService helperService;

    @Autowired
    FeeService feeService;

    @Autowired
    CertificateService certificateService;


    @GetMapping("/select")
    @Transactional
    public Result selectSixPatents(String name, int start) {
        List<Patent> patents = patentService.selectSixPatents(name, start);
        for (Patent p : patents) {
            PatentApplicant patentApplicant = patentApplicantService.selectByPatentId(p.getId());
            Applicant applicant = applicantService.selectById(patentApplicant.getApplicantId());
            p.getApplicants().add(applicant);
        }
        return Result.success(patents);
    }

    @PostMapping("/add")
    @Transactional
    public Result addPatent(@RequestBody PatentDocumentDto patentDocumentDto) {
        //插入Document得到documentId
        Document document = documentService.insertDocument(patentDocumentDto);
        //插入Patent
        Patent patent = patentService.insertPatent(patentDocumentDto, document.getId());
        return Result.success(patent);
    }

    @PostMapping("/addP&A/{contactId}/{patentId}")
    public Result addPatentApplicant(@PathVariable(name = "contactId") int contactId, @PathVariable(name = "patentId") Long patentId, @RequestBody List<Long> applicantIds) {
        //插入关联表
        patentApplicantService.insertPatentApplicants(contactId, patentId, applicantIds);
        return Result.success("成功");
    }


    @GetMapping("/getP&H")
    @Transactional
    public Result selectPatentAndHelper(Long id, String name, int current, int size,int status1,int status2) {
        //使用用户id查询申请人
        Applicant applicant = applicantService.selectByUserId(id);
        //根据申请人id查询所有的patentId
        List<PatentApplicant> patentApplicants = patentApplicantService.selectByApplicantId(applicant.getId());
        List<Long> ids = new ArrayList<>();
        patentApplicants.forEach(patentApplicant -> {
            if(patentApplicant.getContact()==1L){
                ids.add(patentApplicant.getPatentId());
            }
        });
        int total=0;
        List<Long> patentIds = patentApplicants.stream().map(pa ->
                pa.getPatentId()
        ).collect(Collectors.toList());
        if(status1==5&&status2==6){
            total = patentService.selectAllPatents(patentIds, name, 1, 1000, 5,6).size();
        }else {
            total=patentIds.size();
        }
        //根据patentId查出所有专利
        List<Patent> patents = patentService.selectAllPatents(patentIds, name, current, size,status1,status2);
        List<PatentHelperDto> patentHelperDtos = new ArrayList<>();
        for (int i = 0; i < patents.size(); i++) {
            PatentHelperDto patentHelperDto = new PatentHelperDto();
            patentHelperDto.setPatent(patents.get(i));
            patentHelperDto.setHelper(helperService.selectHelpersById(patents.get(i).getHelperId()).get(0));
            patentHelperDto.setTotal(total);
            System.out.println();
            if (ids.contains(patents.get(i).getId())) {
                patentHelperDto.setContact(true);
            }
            patentHelperDtos.add(patentHelperDto);
        }
        return Result.success(patentHelperDtos);
    }

    @PostMapping("/statusChange/{status}/{id}")
    public Result changeStatus(@PathVariable(name = "status") String status, @PathVariable(name = "id") Long id) {
        int i = 0;
        if ("assessment".equals(status)) {
            i = patentService.updateStatus(id, 1);
        } else if ("apply".equals(status)) {
            i = patentService.updateStatus(id, 3);
        } else if ("revokeAssessment".equals(status)) {
            i = patentService.updateStatus(id, 0);
        } else if ("revokeApply".equals(status)) {
            i = patentService.updateStatus(id, 2);
        }else if ("revokeSole".equals(status)) {
            i = patentService.updateStatus(id, 5);
        }else if ("sole".equals(status)) {
            i = patentService.updateStatus(id, 6);
        }
        return Result.success(i);
    }

    @GetMapping("/selectP&A/{patentId}")
    public Result selectPatentAndApplicants(@PathVariable(name = "patentId") Long patentId) {
        Patent patent = patentService.selectPatent(patentId);
        //查到有哪些申请人id
        List<PatentApplicant> patentApplicants = patentApplicantService.selectPatents(patentId);
        List<Long> applicantIds = new ArrayList<>();
        long id = 0L;
        for (int i = 0; i < patentApplicants.size(); i++) {
            applicantIds.add(patentApplicants.get(i).getApplicantId());
            if (patentApplicants.get(i).getContact() == 1L) {
                id = patentApplicants.get(i).getApplicantId();
            }
        }
        List<Applicant> applicants = applicantService.selectByIds(applicantIds);
        long finalId = id;
        applicants.forEach(applicant -> {
            if (applicant.getId() == finalId) {
                applicant.setHasContact(true);
            }
        });
        patent.setApplicants(applicants);
        List<Helper> helpers = helperService.selectHelpersById(patent.getHelperId());
        PatentHelperDto patentHelperDto = new PatentHelperDto();
        patentHelperDto.setPatent(patent);
        patentHelperDto.setHelper(helpers.get(0));
        return Result.success(patentHelperDto);
    }

    @GetMapping("/selectD/{patentId}")
    public Result selectDocument(@PathVariable(name = "patentId") Long patentId) {
        Patent patent = patentService.selectPatent(patentId);
        Document document = documentService.selectById(patent.getDocumentId());
        PatentDocumentDto patentDocumentDto = new PatentDocumentDto();
        patentDocumentDto.setName(patent.getName());
        patentDocumentDto.setContent(patent.getContent());
        patentDocumentDto.setIntroduce(document.getIntroduce());
        patentDocumentDto.setField(document.getField());
        patentDocumentDto.setBackground(document.getBackground());
        patentDocumentDto.setType(patent.getType());
        patentDocumentDto.setSuggestion(patent.getSuggestion());
        return Result.success(patentDocumentDto);
    }

    @PostMapping("/delete")
    @Transactional
    public Result deletePatents(@RequestBody List<Long> ids) {
        //删除关联表信息
        patentApplicantService.deletePatentApplicant(ids);
        //删除document信息
        ids.forEach(id->{
            Patent patent = patentService.selectPatent(id);
            documentService.deleteById(patent.getDocumentId());
        });
        //删除专利表信息
        patentService.deletePatents(ids);
        return Result.success("删除成功");
    }

    @GetMapping("/fee/{id}")
    @Transactional
    public Result selectFee(@PathVariable(name = "id")Long id) {
        Patent patent = patentService.selectPatent(id);
        Fee fee = feeService.selectById(patent.getFeeId());
        return Result.success(fee);
    }

    @GetMapping("/certificate/{id}")
    @Transactional
    public Result selectCertificate(@PathVariable(name = "id")Long id) {
        Patent patent = patentService.selectPatent(id);
        Certificate certificate = certificateService.selectById(patent.getCertificateId());
        return Result.success(certificate);
    }
}
